package exquery.util

import org.apache.log4j.Logger
import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib
import exquery.valuebeans.export.*
import setupx.entity.ExperimentClass
import setupx.entity.Experiment
import exquery.ExperimentClassService
import exquery.ClassSampleService
import setupx.entity.ClassSample
import setupx.entity.ClassMetadata
import setupx.entity.SampleMetadata

/**
 * User: pradeep
 * Date: Jul 3, 2010
 * Time: 6:44:43 PM
 * Format data for export and displaying
 */
class FormatResultUtil {

  Logger gLogger = Logger.getLogger( FormatResultUtil.class)
  private static  FormatResultUtil instance = null
  def g = new ApplicationTagLib()
  ExperimentClassService classService = new ExperimentClassService()
  ClassSampleService sampleService = new ClassSampleService()

  /**
   * returns the instance
   * @return
   */
  public static  FormatResultUtil getInstance() {
    if (instance == null) {
      instance = new  FormatResultUtil()
    }

    return instance
  }

  /**
   * prepare experiments result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareExperimentsResult(def resultList,Map params = [:],boolean isExport = false){

    gLogger.info "coming into prepareExperimentsResult method of FormatResultUtil"

    List fieldList = ["SrNo","id","title","experimentAbstract","description","comments","classesCount","samplesCount"]
    Map labelMap = ["SrNo":"Sr. No.","id":"Experiment Id","title":"Title","experimentAbstract":"Abstract","description":"Description","comments":"Comments","classesCount":"Classes Count","samplesCount":"Samples Count"]

    if( params.format == "xml" ){
      //labelMap = ["SrNo":"SrNo","id":"id","title":"title","experimentAbstract":"experimentAbstract","description":"description","comments":"comments"]
      labelMap = createLabelMapForXML(fieldList)
    }


    Map formatters = [:]
    Map parameters = [:]
    Map cssClassMap = ["SrNo":"srno-no-break","id":"text-no-break","title":"text-with-largespace-break","experimentAbstract":"text-with-largespace-break","description":"text-with-break","comments":"text-with-largespace-break","classesCount":"text-with-break","samplesCount":"text-with-break"]
    List formatedList = null

    if (resultList != null && resultList.size() > 0) {
       ExperimentVO experimentVO
      formatedList = new ArrayList()
      def id = "None"
      def title = "None"
      def Abstract = "None"
      def description = "None"
      def comment = "None"
      def classesCount
      def samplesCount
      long cnt = 0;

      if(!isExport){
        if( params?.offset != null )
        {
            cnt = Long.parseLong("0"+params?.offset.toString());
        }
      }else{
        parameters = [title: "Experiment Search Result", "column.widths": [0.05, 0.1, 0.1, 0.25, 0.1, 0.25,0.05,0.05]]
      }

      if(!isExport){
          fieldList.add("exportExperiment")
          labelMap.put("exportExperiment","Export Experiment(s)")
          cssClassMap.put("exportExperiment","text-with-break")
      }

      resultList?.sort{it.id}.reverse().each {Experiment experiment->
        if( experiment!=null){
          id = experiment?.id
          title = experiment?.getTitle()
          Abstract = experiment?.getExperiment_abstract()
          description = experiment?.getDescription()
          comment = experiment?.getComments()
          classesCount = classService.getClassesCountByExperimentIds(Long.parseLong("0"+id.toString()))
          samplesCount = sampleService.getSamplesCountByExperimentIds(Long.parseLong("0"+id.toString()))
          if(isExport){
            experimentVO = new  ExperimentVO()

            experimentVO.setSrNo(++cnt)
            experimentVO.setId id
            experimentVO.setTitle title
            experimentVO.setExperimentAbstract Abstract
            experimentVO.setDescription description
            experimentVO.setComments comment

            experimentVO.setClassesCount classesCount
            experimentVO.setSamplesCount samplesCount

            formatedList.add(experimentVO)
          }else{
            // Start : Create dynamic link
            def linkExperiment = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${id}"]]) { id }
            def linkExportExperiment = g.link([controller:"search",action:"exportexp",params:[id:"${id}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}
            //gLogger linkId
            // End : Create dynamic link

            formatedList.add(["SrNo":++cnt,"id":linkExperiment,"title":CommonUtil.getInstance().customEncodeAsHTML(title),"experimentAbstract":CommonUtil.getInstance().customEncodeAsHTML(Abstract),"description":CommonUtil.getInstance().customEncodeAsHTML(description),"comments":CommonUtil.getInstance().customEncodeAsHTML(comment),"ExperimentId":id,"classesCount":classesCount,"samplesCount":samplesCount,"exportExperiment":linkExportExperiment] )
          }
        }
      }

    }
    //println formatedList
    gLogger.info formatedList?.size
    gLogger.info "Out from prepareExperimentsResult method of FormatResultUtil"
    return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }

  /**
   * create lable map for export, b'coz in case of export to xml blank spaces are not allowed
   * @param fieldList
   * @return
   */
  private Map createLabelMapForXML(List fieldList){
    Map labelMap = [:]
    fieldList.each { str ->
       labelMap.put(str,str)
    }
    return labelMap
  }

  /**
   * prepare classes result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareClassesResult(def resultList,Map params = [:],boolean isExport = false){

    gLogger.info "coming into prepareClassesResult method of FormatResultUtil"
    gLogger.info "isExport :: ${isExport}"

    //List fieldList = ["SrNo","id","experimentId","organName","extraction","tissue","green_house","genotype","splitratio","detailed_location","preparation","growing_place_media","seeding_date","transplanting_date","harvest_date","night_humidity","day_humidity","night_temperature","day_temperature","light_daily_period","light_fluence","light_source","lamp_detailed","methodName","cell_type","subcellular_celltype"]
    List fieldList = ["SrNo","id","experimentId","speciesName","organName","tissue","cellType","subcellularCelltype","genotype","methodName","samplesCount"]
    Map labelMap = ["SrNo":"Sr. No.","id":"Class Id","experimentId":"Experiment Id","organName":"Organ Name","speciesName":"Species Name","extraction":"Extraction","tissue":"Tissue","green_house":"Green House","genotype":"Genotype","detailed_location":"Detailed Location","preparation":"Preparation","methodName":"Method Name","cellType":"Cell Type","subcellularCelltype":"Subcellular Celltype","samplesCount":"Samples Count in Class"]

    if( params.format == "xml" ){
      labelMap = createLabelMapForXML(fieldList)
    }

    Map formatters = [:]
    Map parameters = [:]
    Map cssClassMap = ["SrNo":"srno-no-break","id":"text-no-break","experimentId":"text-no-break","organName":"text-with-break","speciesName":"text-with-break","extraction":"text-with-break","tissue":"text-with-break","green_house":"text-with-break","genotype":"text-with-break","detailed_location":"text-with-break","preparation":"text-with-break","methodName":"text-with-break","cellType":"text-with-break","subcellularCelltype":"text-with-break","samplesCount":"text-with-break"]

    List formatedList = null

    if (resultList != null && resultList.size() > 0) {
      formatedList = new ArrayList()
       ExperimentClassVO experimentClassVO
      def id = "None"
      def extraction = "None"
      def green_house = "None"
      def genotype = "None"

      def detailed_location = "None"
      def preparation = "None"
      def information = "None"

      def method_name = "None"
      def tissue = "None"
      def cell_type = "None"
      def subcellular_celltype = "None"
      def experimentId = "None"

      //def speciesSet
      def speciesName = "None"

      //def organsSet
      def organsName = "None"
      def samplesCount = 0L
      def classMetaDataSet

      long cnt = 0;

      def metaDataCols=[]
      def metaDataDesc=[:]

      resultList.each {ExperimentClass experimentClass->
         if( experimentClass!=null){
             classMetaDataSet = experimentClass?.classMetadataSet
             if(classMetaDataSet!=null && classMetaDataSet.size()>0){
                 classMetaDataSet.each {ClassMetadata classMetadata->
                    if(classMetadata!=null){
                       if(!metaDataCols.contains(classMetadata.fieldLogicalId.toString())){
                          metaDataCols.add(classMetadata.fieldLogicalId.toString())
                          metaDataDesc.put(classMetadata.fieldLogicalId.toString(),classMetadata.fieldTitle)
                       }
                    }
                 }
             }//end if classMetaData
         }//end if experimentClass
      }
      gLogger.info("metaDataCols :: ${metaDataCols}")
      gLogger.info("metaDataDesc :: ${metaDataDesc}")

      if(!isExport){
        if( params?.offset != null )
        {
            cnt = Long.parseLong("0"+params?.offset.toString());
        }

        fieldList.add("classMetaData")
        fieldList.add("exportExperiment")

        labelMap.put("classMetaData","Meta Data(s)")
        labelMap.put("exportExperiment","Export Experiment(s)")

        cssClassMap.put("classMetaData","text-with-largespace-break")
        cssClassMap.put("exportExperiment","text-with-break")

      }else{
        //parameters = [title: "Class Search Result", "column.widths": [0.05, 0.05, 0.075, 0.15, 0.1,0.1, 0.15, 0.15, 0.075, 0.075,0.05]]
          parameters = [title: "Class Search Result"]

          if(metaDataCols!=null){
              metaDataCols = metaDataCols?.sort{it.toString()}
              metaDataCols.each {meta->
                fieldList.add(meta.toString())
                labelMap.put(meta.toString(),metaDataDesc.get(meta.toString()).toString())
                cssClassMap.put(meta.toString(),"text-with-break")
              }
          }
      }
      def meataDataString=""
      resultList?.sort{it.experiment.id}.reverse().each {ExperimentClass experimentClass->
        if( experimentClass != null ){

          id = experimentClass.id
          extraction = experimentClass.getExtraction()
          green_house = experimentClass.getGreen_house()
          genotype = experimentClass.getGenotype()

          detailed_location = experimentClass.getDetailed_location()
          preparation = experimentClass.getPreparation()
          information = experimentClass.getInformation()


          method_name = experimentClass.getMethod_name()
          experimentId = experimentClass.experiment.id

          samplesCount = sampleService.getSamplesCountByClassIds(experimentClass.id)

          /* set the species info : Start */
          speciesName = CommonUtil.getInstance().prepareSpeciesText(experimentClass?.speciesSet)
          /* set the species info : End */

          /* set the organs info : Start */
          organsName = CommonUtil.getInstance().prepareOrgansText(experimentClass?.organSet)
          tissue = CommonUtil.getInstance().prepareOrgansTissueText(experimentClass?.organSet)
          cell_type = CommonUtil.getInstance().prepareOrgansCellTypeText(experimentClass?.organSet)
          subcellular_celltype = CommonUtil.getInstance().prepareOrgansSubcellularCelltype(experimentClass?.organSet)

          /* set the organs info : End */
          classMetaDataSet = experimentClass?.classMetadataSet
          if(isExport){
//            experimentClassVO = new  ExperimentClassVO()
//
//            experimentClassVO.setSrNo( ++cnt )
//            experimentClassVO.setId id
//            experimentClassVO.setExperimentId experimentId
//            experimentClassVO.setOrganName organsName
//            experimentClassVO.setSpeciesName speciesName
//            experimentClassVO.setTissue tissue
//            experimentClassVO.setGenotype genotype
//            experimentClassVO.setMethodName method_name
//            experimentClassVO.setCellType cell_type
//            experimentClassVO.setSubcellularCelltype subcellular_celltype
//
//            experimentClassVO.setSamplesCount samplesCount
              def map = ["SrNo":++cnt,"id":id,"experimentId":experimentId,"organName":organsName,"speciesName":speciesName,"extraction":extraction,"tissue":tissue,"green_house":green_house,"genotype":genotype,"information":information,"detailed_location":detailed_location,"preparation":preparation,"methodName":method_name,"cellType":cell_type,"subcellularCelltype":subcellular_celltype,"samplesCount":samplesCount]


              if(classMetaDataSet!=null && classMetaDataSet.size()>0){
                if(metaDataCols!=null){
                    metaDataCols?.each {meta->
                        String value=""
                        def tempClassMetaDataSet   = ExportExperimentUtil.getInstance().getClassMetadataByLogicalFieldId(classMetaDataSet,meta?.toString())
                        if(tempClassMetaDataSet!=null && tempClassMetaDataSet.size()>0){
                          tempClassMetaDataSet.each {ClassMetadata metaData->
                              if(metaData!=null && metaData.fieldValue !=null && metaData.fieldValue.toString().trim().length()!=0 ){
                                 if(value.trim().length()==0){
                                     value = HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())
                                     //gLogger.info HTMLDecoder.getInstance().decode(value)
                                 }else{
                                     value += "; ${HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())}"
                                 }
                              }
                          }
                        }
                        map.put(meta.toString(),value)
                    }
                }
              }
              formatedList.add(map)
          }else{
            // Start : Create dynamic link
            def linkClass = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentClassId",id:"${id}"]]) { id }
            def linkExperiment = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${experimentId}"]]) { experimentId }
            def linkExportExperiment = g.link([controller:"search",action:"exportexp",params:[id:"${experimentId}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}
            // End : Create dynamic link
            meataDataString = ""
            if(classMetaDataSet!=null && classMetaDataSet.size()>0){
                if(metaDataCols!=null){
                    metaDataCols?.each {meta->
                        String value=""
                        def tempClassMetaDataSet   = ExportExperimentUtil.getInstance().getClassMetadataByLogicalFieldId(classMetaDataSet,meta?.toString())
                        if(tempClassMetaDataSet!=null && tempClassMetaDataSet.size()>0){
                          tempClassMetaDataSet.each {ClassMetadata metaData->
                              if(metaData!=null && metaData.fieldValue !=null && metaData.fieldValue.toString().trim().length()!=0 ){
                                 if(value.trim().length()==0){
                                     value = HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())
                                     //gLogger.info HTMLDecoder.getInstance().decode(value)
                                 }else{
                                     value += "; ${HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())}"
                                 }
                              }
                          }
                        }

                        if(value!=null && value.toString().trim().length()>0){
                            if(meataDataString.length()>0 ){
                                meataDataString += "<br><span class=\"forminputlabel\">${metaDataDesc.get(meta.toString()).toString()}</span>= ${value != null ? value : ''}"
                            } else{
                                meataDataString = "<span class=\"forminputlabel\">${metaDataDesc.get(meta.toString()).toString()}</span>= ${value != null ? value : ''}"
                            }
                        }
                    }
                }
              }

            formatedList.add(["SrNo":++cnt,"id":linkClass,"experimentId":linkExperiment,"organName":organsName,"speciesName":speciesName,"extraction":extraction,"tissue":tissue,"green_house":green_house,"genotype":genotype,"information":information,"detailed_location":detailed_location,"preparation":preparation,"methodName":method_name,"cellType":cell_type,"subcellularCelltype":subcellular_celltype,"samplesCount":samplesCount,"classMetaData":meataDataString,"exportExperiment":linkExportExperiment])
          }
        }
      }
    }
    //println formatedList
    gLogger.info formatedList?.size
    gLogger.info "Out from prepareClassesResult method of FormatResultUtil"
    return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }

  /**
   * prepare samples result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareSamplesResult(def resultList,Map params = [:],boolean isExport = false){

    gLogger.info "coming into prepareSamplesResult method of FormatResultUtil"

    List fieldList = ["SrNo","id","classId","experimentId","label","chromatof","genotype","speciesName","organsName","tissue"]
    Map labelMap = ["SrNo":"Sr. No.","id":"Sample Id","classId":"Class Id","experimentId":"Experiment Id","label":"Label","chromatof":"chromatof Ids","genotype":"Genotype","organsName":"OrganName","speciesName":"SpeciesName","tissue":"Tissue"]
    if( params.format == "xml" ){
      labelMap = createLabelMapForXML(fieldList)
    }
    Map formatters = [:]
    Map parameters = [:]
    Map cssClassMap = ["SrNo":"srno-no-break","id":"text-no-break","classId":"text-no-break","experimentId":"text-no-break","label":"text-with-break","chromatof":"text-with-break","genotype":"text-with-break","organsName":"text-with-break","speciesName":"text-with-break","tissue":"text-with-break"]
    List formatedList = null

    if (resultList != null && resultList.size() > 0) {
      formatedList = new ArrayList()
       ClassSampleVO classSampleVO
      def id = "None"
      def class_id = "None"
      def experiment_id = "None"
      def label = "None"
      def genotype = "None"
      def tissue = "None"
      def speciesName= "None"
      def organsName= "None"


      def variations
      String variationsString
      String chromatofIds

      long cnt = 0;

      def metaDataCols=[]
      def metaDataDesc=[:]

      if(resultList!=null && resultList.size()>0){
          resultList.each {ClassSample sample->
            def sampleMetaDataSet = sample?.sampleMetadataSet
            //println "${sample.id}-> sampleMetaDataSet :: ${sampleMetaDataSet}"
            if(sampleMetaDataSet!=null && sampleMetaDataSet.size()>0){
                 sampleMetaDataSet.each {SampleMetadata sampleMetadata->
                    if(sampleMetadata!=null){
                       if(!metaDataCols.contains(sampleMetadata.fieldLogicalId.toString())){
                          metaDataCols.add(sampleMetadata.fieldLogicalId.toString())
                          metaDataDesc.put(sampleMetadata.fieldLogicalId.toString(),sampleMetadata.fieldTitle)
                       }
                    }
                 }
             }//end if sampleMetaData
          }// end each resultList
      }//end if resultList

      gLogger.info("metaDataCols :: ${metaDataCols}")
      gLogger.info("metaDataDesc :: ${metaDataDesc}")

      if(!isExport){
        if( params?.offset != null )
        {
            cnt = Long.parseLong("0"+params?.offset.toString());
        }

        fieldList.add("sampleMetaData")
        fieldList.add("exportExperiment")

        labelMap.put("sampleMetaData","Variation(s)")
        labelMap.put("exportExperiment","Export Experiment(s)")

        cssClassMap.put("sampleMetaData","text-with-largespace-break")
        cssClassMap.put("exportExperiment","text-with-break")

      }else{
        parameters = [title: "Sample Search Result"]//, "column.widths": [0.05, 0.06, 0.05, 0.075, 0.175, 0.15, 0.15,0.1, 0.2]]

        //Add meta columns header into result
        if(metaDataCols!=null){
          metaDataCols = metaDataCols?.sort{it.toString()}
          metaDataCols.each {meta->
            fieldList.add(meta.toString())
            labelMap.put(meta.toString(),metaDataDesc.get(meta.toString()).toString())
            cssClassMap.put(meta.toString(),"text-with-break")
          }
        }
      }

      //List MetaDataList = prepareSampleMetaDataList(resultList);
      //gLogger.info "prepareSampleMetaDataList :: ${MetaDataList}"

      ExperimentClass experimentClass
      resultList?.sort{it?.experimentclass?.experiment?.id}.reverse().each { sample->
        if(sample!=null){
          id = sample?.id
          class_id = sample?.experimentclass?.id
          experiment_id = sample?.experimentclass?.experiment?.id
          label = sample?.getLabel()
          def sampleMetaDataSet = sample?.sampleMetadataSet
          //gLogger.info "variations :: "+variations

          chromatofIds = CommonUtil.getInstance().prepareChromatofsString(sample?.sampleChromatofSet)

          experimentClass = sample?.experimentclass
          genotype = experimentClass?.getGenotype()


          /* set the species info : Start */
          speciesName = CommonUtil.getInstance().prepareSpeciesText(experimentClass?.speciesSet)
          /* set the species info : End */

          /* set the organs info : Start */
          organsName = CommonUtil.getInstance().prepareOrgansText(experimentClass?.organSet)
          tissue = CommonUtil.getInstance().prepareOrgansTissueText(experimentClass?.organSet)
          /* set the organs info : End */


          variationsString = ""
          if(isExport){
//            classSampleVO = new  ClassSampleVO()
//
//            classSampleVO.setSrNo(++cnt)
//            classSampleVO.setId id
//            classSampleVO.setClassId class_id
//            classSampleVO.setExperimentId experiment_id
//            classSampleVO.setLabel label
//            classSampleVO.setChromatof chromatofIds
//
//            classSampleVO.setGenotype genotype
//            classSampleVO.setTissue tissue
//            classSampleVO.setOrgansName organsName
//            classSampleVO.setSpeciesName speciesName
//
//            def metaData
//            MetaDataList.each { logicalId->
//               metaData = getMetaDataObjectFromSet(logicalId,variations)
//               if(metaData!=null){
//                 if(variationsString.length()>0 ){
//                    variationsString += "; ${metaData.fieldTitle}=${metaData.fieldValue != null ? metaData.fieldValue : '' }"
//                 } else{
//                    variationsString = "${metaData.fieldTitle}=${metaData.fieldValue != null ? metaData.fieldValue : ''}"
//                 }
//               }
//            }
//
//            classSampleVO.setSampleMetaData variationsString
              def map = ["SrNo":++cnt,"id":id,"classId":class_id,"experimentId":experiment_id,"label":label,"chromatof":chromatofIds,"genotype":genotype,"organsName":organsName,"speciesName":speciesName,"tissue":tissue]

              if(sampleMetaDataSet!=null && sampleMetaDataSet.size()>0){
                  if(metaDataCols!=null){
                    metaDataCols?.each {meta->
                        String value=""
                        def tempSampleMetaDataSet   = ExportExperimentUtil.getInstance().getSampleMetadataByLogicalFieldId(sampleMetaDataSet,meta?.toString())
                        if(tempSampleMetaDataSet!=null && tempSampleMetaDataSet.size()>0){
                          tempSampleMetaDataSet.each {SampleMetadata metaData->
                              if(metaData!=null && metaData.fieldValue !=null && metaData.fieldValue.toString().trim().length()!=0 ){
                                 if(value.trim().length()==0){
                                     value = HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())
                                     //gLogger.info HTMLDecoder.getInstance().decode(value)
                                 }else{
                                     value += "; ${HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())}"
                                 }
                              }//end if metaData
                          }//end each tempSampleMetaDataSet
                        }//end if tempSampleMetaDataSet

                        map.put(meta.toString(),value)
                    }//end each metaDataCols
                  }//end if metaDataCols
              }//end if sampleMetaDataSet

              formatedList.add(map)
          }else{
            // Start : Create dynamic link
            def linkSample = g.link([controller:"search",action:"showInfo",params:[infoBy:"ClassSampleId",id:"${id}"]]) { id }
            def linkClass = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentClassId",id:"${class_id}"]]) { class_id }
            def linkExperiment = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${experiment_id}"]]) { experiment_id }
            def linkExportExperiment = g.link([controller:"search",action:"exportexp",params:[id:"${experiment_id}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}
            // End : Create dynamic link

            if(sampleMetaDataSet!=null && sampleMetaDataSet.size()>0){
              if(metaDataCols!=null){
                metaDataCols?.each {meta->
                    String value=""
                    def tempSampleMetaDataSet   = ExportExperimentUtil.getInstance().getSampleMetadataByLogicalFieldId(sampleMetaDataSet,meta?.toString())
                    if(tempSampleMetaDataSet!=null && tempSampleMetaDataSet.size()>0){
                      tempSampleMetaDataSet.each {SampleMetadata metaData->
                          if(metaData!=null && metaData.fieldValue !=null && metaData.fieldValue.toString().trim().length()!=0 ){
                             if(value.trim().length()==0){
                                 value = HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())
                                 //gLogger.info HTMLDecoder.getInstance().decode(value)
                             }else{
                                 value += "; ${HTMLDecoder.getInstance().decode(metaData.fieldValue.toString())}"
                             }
                          }//end if metaData
                      }//end each tempSampleMetaDataSet
                    }//end if tempSampleMetaDataSet

                    if(value!=null && value.toString().trim().length()>0){
                        if(variationsString.length()>0 ){
                            variationsString += "<br><span class=\"forminputlabel\">${metaDataDesc.get(meta.toString()).toString()}</span>= ${value != null ? value : ''}"
                        } else{
                            variationsString = "<span class=\"forminputlabel\">${metaDataDesc.get(meta.toString()).toString()}</span>= ${value != null ? value : ''}"
                        }
                    }
                }//end each metaDataCols
              }//end if metaDataCols
            }//end if sampleMetaDataSet

            formatedList.add(["SrNo":++cnt,"id":linkSample,"classId":linkClass,"experimentId":linkExperiment,"label":label,"chromatof":chromatofIds,"genotype":genotype,"organsName":organsName,"speciesName":speciesName,"tissue":tissue,"sampleMetaData":variationsString,"exportExperiment":linkExportExperiment] )
          }

        }
      }
    }
    //println formatedList
    gLogger.info formatedList?.size
    gLogger.info "Out from prepareSamplesResult method of FormatResultUtil"
    return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }

  /**
   * Generate sorted list of logical ids for sample metadata
   * @param resultList
   * @return
   */
  public List prepareSampleMetaDataList(def resultList){
    List list = []
    List restrictList = ['COMMENT','EVENTS','LABEL']
    def variations
    resultList?.each {  sample->
      if(sample!=null){
        variations = sample?.sampleMetadataSet
        variations.each { metaData->
          if( !restrictList.contains(metaData.fieldLogicalId) && !list.contains(metaData.fieldLogicalId)){
            list.add(metaData.fieldLogicalId)
          }
        }
      }
    }

    return list?.sort()
  }

  /**
   * Get SampleMetaData Object for logicalId
   * @param logicalId
   * @param variations
   * @return
   */
  private def getMetaDataObjectFromSet(String logicalId,def variations){
     def resultMetaData
     variations.each { metaData->
        if( logicalId.equals(metaData.fieldLogicalId.toString()) ) {
          resultMetaData = metaData
        }
     }
    return resultMetaData
  }


  /**
   * prepare species result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareSpeciesResult(def resultList,Map params = [:],boolean isExport = false){

    gLogger.info "coming into prepareSpeciesResult method of FormatResultUtil"

    List fieldList = ["SrNo","speciesName","ncbiId","scientificName","synonyms","experimentCount","classesCount","samplesCount","organs"]
    Map labelMap = ["SrNo":"Sr. No.","speciesName":"Species Name","ncbiId":"NCBI Id","scientificName":"Scientific Name","synonyms":"Synonym(s)","experimentCount":"Experiment Count","classesCount":"Classes Count","samplesCount":"Samples Count","organs":"Organ(s)"]

    Map formatters = [:]
    Map parameters = [:]
    Map cssClassMap = ["SrNo":"srno-no-break","speciesName":"text-no-break","ncbiId":"text-no-break","scientificName":"text-no-break","synonyms":"text-with-largespace-break","experimentCount":"text-no-break","classesCount":"text-no-break","samplesCount":"text-no-break","organs":"text-with-largespace-break"]
    List formatedList = null

    if (resultList != null && resultList.size() > 0) {
      formatedList = new ArrayList()
      //SpeciesVO speciesVO
      def speciesName = "None"
      def ncbiId = "None"
      def scientificName = "None"
      def synonyms = "None"
      def organs = "None"

      def experimentCount = "None"
      def classesCount = "None"
      def samplesCount = "None"

      long cnt = 0;

      if(!isExport){
          fieldList.add("exportExperiment")
          labelMap.put("exportExperiment","Export Experiment(s)")
          cssClassMap.put("exportExperiment","text-with-break")
      }

      if(!isExport){

        if( params?.offset != null )
        {
            cnt = Long.parseLong("0"+params?.offset.toString());
        }
      }else{

        parameters = [title: "Species Search Result", "column.widths": [0.075, 0.125, 0.075,0.125,0.2,0.075,0.075,0.075,0.175]]
        //parameters = [title: "Species Search Result"]
      }

      if( params.format == "xml" ){
        //labelMap = createLabelMapForXML(fieldList)
      }



      resultList.each {SpeciesVO speciesVO->
        if(speciesVO!=null){
          speciesName = speciesVO.speciesName
          ncbiId = speciesVO.ncbiId
          scientificName = speciesVO.scientificName
          synonyms = CommonUtil.getInstance().convertNameListIntoString(speciesVO.synonyms)
          organs = CommonUtil.getInstance().convertNameListIntoString(speciesVO.organs)
          experimentCount = speciesVO.experimentCount
          classesCount = speciesVO.classesCount
          samplesCount = speciesVO.samplesCount


          if(isExport){
              speciesVO.setSynonyms(synonyms)
              speciesVO.setOrgans(organs)
              speciesVO.setSrNo(++cnt)
              formatedList.add(speciesVO)
          }else{
            // Start : Create dynamic link
            def linkNcbiId = "<a href=\"http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=${ncbiId}&lvl=3&lin=f&keep=1&srchmode=1&unlock\" target=\"_blank\" title=\"Click to get more info\">NCBI: ${ncbiId}</a>"//g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${ncbiId}"]]) { ncbiId }
            def linkExperiment = g.link([controller:"species",action:"datalist",params:[lookupBy:"experiments",speciesName:"${speciesName}"]]) { experimentCount }
            def linkClass = g.link([controller:"species",action:"datalist",params:[lookupBy:"classes",speciesName:"${speciesName}"]]) { classesCount }
            def linkSample = g.link([controller:"species",action:"datalist",params:[lookupBy:"samples",speciesName:"${speciesName}"]]) { samplesCount }
            def linkExportExperiment = g.link([controller:"species",action:"exportexp",params:[speciesName:"${speciesName}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}
            // End : Create dynamic link

            formatedList.add(["SrNo":++cnt,"speciesName":speciesName,"ncbiId":linkNcbiId,"scientificName":scientificName,"synonyms":synonyms,"experimentCount":linkExperiment,"classesCount":linkClass,"samplesCount":linkSample,"organs":organs,"exportExperiment":linkExportExperiment] )
          }

      }
    }
    }
    //println formatedList
    gLogger.info formatedList?.size
    gLogger.info "Out from prepareSpeciesResult method of FormatResultUtil"
    return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }

    /**
     * generate sample list out of sample set
     * @param sampleSet
     * @return
     */
  private def prepareSamplesList(def sampleSet){
      def sampleVOList = new ArrayList()

      def id = "None"
      def class_id = "None"
      def experiment_id = "None"
      def label = "None"
      def comment = "None"
      def event = "None"
      def Chromatofs
      def variations
      String variationsString
      String chromatofIds

      long cnt = 0;

      List MetaDataList = prepareSampleMetaDataList(sampleSet);
      gLogger.info "prepareSampleMetaDataList :: ${MetaDataList}"
      ClassSampleVO classSampleVO
      sampleSet.each { sample->
        if(sample!=null){
          chromatofIds = ""
          id = sample?.id
          class_id = sample?.experimentclass?.id
          experiment_id = sample?.experimentclass?.experiment?.id
          label = sample?.getLabel()
          comment = sample?.getComments()
          event = sample?.getEvent()
          variations = sample?.sampleMetadataSet
          Chromatofs = sample?.sampleChromatofSet
          gLogger.info "variations :: "+variations

          if( Chromatofs != null ){

              Chromatofs.each { chromatof->
              if( chromatofIds.toString().length() == 0 ){
                  chromatofIds = chromatof.getChromatofFileId()
              }else{
                  chromatofIds += "; " + chromatof.getChromatofFileId()
              }
            }
          }

          variationsString = ""

          classSampleVO = new  ClassSampleVO()

          classSampleVO.setSrNo(++cnt)
          classSampleVO.setId id
          classSampleVO.setClassId class_id
          classSampleVO.setExperimentId experiment_id
          classSampleVO.setLabel label
          classSampleVO.setComments comment
          classSampleVO.setEvent event
          classSampleVO.setChromatof chromatofIds

          def metaData
          MetaDataList.each { logicalId->
             metaData = getMetaDataObjectFromSet(logicalId,variations)
             if(metaData!=null){
               if(variationsString.length()>0 ){
                  variationsString += "; ${metaData.fieldTitle}=${metaData.fieldValue != null ? metaData.fieldValue : '' }"
               } else{
                  variationsString = "${metaData.fieldTitle}=${metaData.fieldValue != null ? metaData.fieldValue : ''}"
               }
             }
          }
          classSampleVO.setSampleMetaData variationsString

          sampleVOList.add(classSampleVO)
        }
      }
    return sampleVOList
  }


  /**
   * prepare organs result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareOrgansResult(def resultList,Map params = [:],boolean isExport = false){

    gLogger.info "coming into prepareOrgansResult method of FormatResultUtil"

    List fieldList = ["SrNo","organName","experimentCount","classesCount","samplesCount","species"]
    Map labelMap = ["SrNo":"Sr. No.","organName":"Organ Name","experimentCount":"Experiment Count","classesCount":"Classes Count","samplesCount":"Samples Count","species":"Species"]

    Map formatters = [:]
    Map parameters = [:]
    Map cssClassMap = ["SrNo":"srno-no-break","organName":"text-no-break","experimentCount":"text-no-break","classesCount":"text-no-break","samplesCount":"text-no-break","species":"text-with-largespace-break"]
    List formatedList = null

    if (resultList != null && resultList.size() > 0) {
      formatedList = new ArrayList()

      def organName = "None"
      def classesCount = "None"
      def experimentCount = "None"
      def samplesCount = "None"
      def species = "None"

      long cnt = 0;

      if(!isExport){
          fieldList.add("exportExperiment")
          labelMap.put("exportExperiment","Export Experiment(s)")
          cssClassMap.put("exportExperiment","text-with-break")
      }

      if(!isExport){
        if( params?.offset != null )
        {
            cnt = Long.parseLong("0"+params?.offset.toString());
        }
      }else{
        parameters = [title: "Organ Search Result", "column.widths": [0.1, 0.2, 0.15, 0.15, 0.15,0.25]]
        //parameters = [title: "Organ Search Result"]
      }

      if( params.format == "xml" ){
        labelMap = createLabelMapForXML(fieldList)
      }

      resultList.each {OrganVO organVO->
        if(organVO){
          organName = organVO.organName
          classesCount = organVO.classesCount
          experimentCount = organVO.experimentCount
          samplesCount = organVO.samplesCount
          species = CommonUtil.getInstance().convertNameListIntoString(organVO.species)

          if(isExport){
              organVO.setSpecies(species)
              organVO.setSrNo(++cnt)
              formatedList.add(organVO)
          }else{
              // Start : Create dynamic link
              def linkExperiment = g.link([controller:"organ",action:"datalist",params:[lookupBy:"experiments",organName:"${organName}"]]) { experimentCount }
              def linkClass = g.link([controller:"organ",action:"datalist",params:[lookupBy:"classes",organName:"${organName}"]]) { classesCount }
              def linkSample = g.link([controller:"organ",action:"datalist",params:[lookupBy:"samples",organName:"${organName}"]]) { samplesCount }
              def linkExportExperiment = g.link([controller:"organ",action:"exportexp",params:[organName:"${organName}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}
              // End : Create dynamic link
              formatedList.add(["SrNo":++cnt,"organName":organName,"experimentCount":linkExperiment,"classesCount":linkClass,"samplesCount":linkSample,"species":species,"exportExperiment":linkExportExperiment] )
          }
        }
      }
    }
    //println formatedList
    gLogger.info formatedList?.size
    gLogger.info "Out from prepareOrgansResult method of FormatResultUtil"
    return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }

  /**
   * prepare user search result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareUserResult(def resultList,Map params = [:],boolean isExport = false){

    gLogger.info "coming into prepareUserResult method of FormatResultUtil"

    List fieldList = ["SrNo","userId","displayName","email","experimentCount","classesCount","samplesCount"]
    Map labelMap = ["SrNo":"Sr. No.","userId":"UserId","displayName":"UserName","email":"eMail Id","experimentCount":"Experiment Count","classesCount":"Classes Count","samplesCount":"Samples Count"]

    Map formatters = [:]
    Map parameters = [:]
    Map cssClassMap = ["SrNo":"srno-no-break","userId":"text-no-break","displayName":"text-no-break","email":"text-no-break","experimentCount":"text-no-break","classesCount":"text-no-break","samplesCount":"text-no-break"]
    List formatedList = null

    if (resultList != null && resultList.size() > 0) {
      formatedList = new ArrayList()

      def userId = "None"
      def displayName = "None"
      def email = "None"
      def classesCount = "None"
      def experimentCount = "None"
      def samplesCount = "None"
      
      long cnt = 0;

      if(!isExport){
          fieldList.add("exportExperiment")
          labelMap.put("exportExperiment","Export Experiment(s)")
          cssClassMap.put("exportExperiment","text-with-break")
      }

      if(!isExport){
        if( params?.offset != null )
        {
            cnt = Long.parseLong("0"+params?.offset.toString());
        }
      }else{
        parameters = [title: "User Search Result", "column.widths": [0.1,0.1,0.25,0.25, 0.1, 0.1, 0.1]]
        //parameters = [title: "Organ Search Result"]
      }

      if( params.format == "xml" ){
        labelMap = createLabelMapForXML(fieldList)
      }

      resultList.each {UserVO userVO->
        if(userVO){
          userId = userVO.userId
          displayName = userVO.displayName
          email = userVO.email
          classesCount = userVO.classesCount
          experimentCount = userVO.experimentCount
          samplesCount = userVO.samplesCount
          
          if(isExport){
              userVO.setSrNo(++cnt)
              formatedList.add(userVO)
          }else{
              // Start : Create dynamic link
              def linkExperiment = experimentCount
              if(experimentCount!=null && experimentCount > 0){
                  linkExperiment = g.link([controller:"owner",action:"datalist",params:[lookupBy:"experiments",id:"${userId}"]]) { experimentCount }
              }

              def linkClass = classesCount
              if(classesCount!=null && classesCount > 0){
                  linkClass = g.link([controller:"owner",action:"datalist",params:[lookupBy:"classes",id:"${userId}"]]) { classesCount }
              }

              def linkSample = experimentCount
              if(samplesCount!=null && samplesCount > 0){
                  linkSample = g.link([controller:"owner",action:"datalist",params:[lookupBy:"samples",id:"${userId}"]]) { samplesCount }
              }

              def linkExportExperiment = ""
              if(experimentCount!=null && experimentCount > 0){
                  linkExportExperiment = g.link([controller:"owner",action:"exportexp",params:[id:"${userId}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}
              }
              // End : Create dynamic link
              formatedList.add(["SrNo":++cnt,"userId":userId,"displayName":displayName,"email":email,"experimentCount":linkExperiment,"classesCount":linkClass,"samplesCount":linkSample,"exportExperiment":linkExportExperiment] )
          }
        }
      }
    }
    //println formatedList
    gLogger.info formatedList?.size
    gLogger.info "Out from prepareUserResult method of FormatResultUtil"
    return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }

  /**
   * prepare search All result for export and listing
   * isExport = false -> is used for listing and
   * isExport = true -> is used for export
   * @param resultList
   * @param params
   * @param isExport
   * @return
   */
  def prepareSearchAllResult(def resultList,Map params = [:],boolean isExport = false){
      gLogger.info "coming into prepareSearchAllResult method of FormatResultUtil"

      List fieldList = ["SrNo","discoveredInObj","ObjectInfo","ExperimentId","exportExperiment"]
      Map labelMap = ["SrNo":"Sr. No.","discoveredInObj":"Discovered in","ObjectInfo":"Object Info","ExperimentId":"Experiment Id","exportExperiment":"Export Experiment"]

      Map formatters = [:]
      Map parameters = [:]
      Map cssClassMap = ["SrNo":"srno-no-break","discoveredInObj":"text-no-break","ObjectInfo":"text-with-largespace-break","ExperimentId":"text-with-break","exportExperiment":"text-with-break"]
      List formatedList = []


      long recCount = 0
      def discoveredInObj
      def tempResult
      def objectInfo
      def experimentId
      def exportExperiment


      if( resultList!=null && resultList?.size()>0){
        resultList.each {data->
            if( data instanceof Experiment){//Process Searched Experiments
                def experiment = (Experiment)data
                //gLogger.info "experiment :: ${experiment}"
                experimentId = experiment.id
                def linkExperiment = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${experimentId}"]]) { experimentId }

                discoveredInObj = "Experiment[${linkExperiment}]"
                exportExperiment = g.link([controller:"search",action:"exportexp",params:[id:"${experimentId}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}

                objectInfo = "<b>Title:</b> ${experiment.title}<br>"
                objectInfo += "<b>Classes Count:</b> "+classService.getClassesCountByExperimentIds(Long.parseLong("0"+experimentId.toString()))+"<br>"
                objectInfo += "<b>Samples Count:</b> "+sampleService.getSamplesCountByExperimentIds(Long.parseLong("0"+experimentId.toString()))

                formatedList.add(["SrNo":++recCount,"discoveredInObj":discoveredInObj,"ObjectInfo":objectInfo,"ExperimentId":linkExperiment,"exportExperiment":exportExperiment])

            }else if( data instanceof ExperimentClass){//Process Searched Classes
                def experimentClass = (ExperimentClass)data
                def linkClass = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentClassId",id:"${experimentClass.id}"]]) { experimentClass.id }

                discoveredInObj = "Class[${linkClass}]"
                //gLogger.info "clazz :: ${experimentClass}"

                experimentId = experimentClass.experiment.id
                def linkExperiment = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${experimentId}"]]) { experimentId }

                exportExperiment = g.link([controller:"search",action:"exportexp",params:[id:"${experimentId}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}

                objectInfo = "<b>Genotype:</b> ${experimentClass.getGenotype()}<br>"
                objectInfo += "<b>Samples Count:</b> "+sampleService.getSamplesCountByClassIds(experimentClass.id)+"<br>"
                objectInfo += "<b>Species:</b> "+CommonUtil.getInstance().prepareSpeciesText(experimentClass?.speciesSet)+"<br>"
                objectInfo += "<b>Organs:</b> "+CommonUtil.getInstance().prepareOrgansText(experimentClass?.organSet)+"<br>"
                objectInfo += "<b>Tissue:</b> ${CommonUtil.getInstance().prepareOrgansTissueText(experimentClass?.organSet)}"


                formatedList.add(["SrNo":++recCount,"discoveredInObj":discoveredInObj,"ObjectInfo":objectInfo,"ExperimentId":linkExperiment,"exportExperiment":exportExperiment])

            }else if( data instanceof ClassSample){//Process Searched Samples
                def sample = (ClassSample)data
                def classId = sample?.experimentclass?.id
                def linkSample = g.link([controller:"search",action:"showInfo",params:[infoBy:"ClassSampleId",id:"${sample.id}"]]) { sample.id }
                def linkClass = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentClassId",id:"${classId}"]]) { classId }

                discoveredInObj = "Sample[${linkSample}]"
                //gLogger.info "sample :: ${sample}"

                experimentId = sample?.experimentclass?.experiment?.id
                def linkExperiment = g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${experimentId}"]]) { experimentId }

                exportExperiment = g.link([controller:"search",action:"exportexp",params:[id:"${experimentId}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}

                objectInfo = "<b>Class Id:</b> ${linkClass}<br>"
                objectInfo += "<b>Label:</b> ${sample?.getLabel()}<br>"
                objectInfo += "<b>Chromatof Ids:</b> "+CommonUtil.getInstance().prepareChromatofsString(sample?.sampleChromatofSet)

                formatedList.add(["SrNo":++recCount,"discoveredInObj":discoveredInObj,"ObjectInfo":objectInfo,"ExperimentId":linkExperiment,"exportExperiment":exportExperiment])

            }else if( data instanceof SpeciesVO){//Process Searched Species
                def species = (SpeciesVO)data

                //gLogger.info "species :: ${species}"

                experimentId = ""
                exportExperiment = ""
                objectInfo = "<b>Scientific Name:</b> ${species.scientificName}<br>"
                objectInfo += "<b>Synonyms:</b> ${CommonUtil.getInstance().convertNameListIntoString(species.synonyms)}<br>"
                objectInfo += "<b>Organs:</b> ${CommonUtil.getInstance().convertNameListIntoString(species.organs)}<br>"

                // Start : Create dynamic link
                def linkNcbiId = "<a href='http://www.ncbi.nlm.nih.gov/Taxonomy/Browser/wwwtax.cgi?mode=Info&id=${species.getNcbiId()}&lvl=3&lin=f&keep=1&srchmode=1&unlock' target='_blank' title='Click to get more info'>NCBI: ${species.getNcbiId()}</a>"//g.link([controller:"search",action:"showInfo",params:[infoBy:"ExperimentId",id:"${ncbiId}"]]) { ncbiId }
                discoveredInObj = "Species["+linkNcbiId+"]"

                if(species?.experimentCount > 0){
                    def linkExperiment = g.link([controller:"species",action:"datalist",params:[lookupBy:"experiments",speciesName:"${species.scientificName}"]]) { species?.experimentCount }
                    def linkClass = g.link([controller:"species",action:"datalist",params:[lookupBy:"classes",speciesName:"${species.scientificName}"]]) { species?.classesCount }
                    def linkSample = g.link([controller:"species",action:"datalist",params:[lookupBy:"samples",speciesName:"${species.scientificName}"]]) { species?.samplesCount }
                    exportExperiment = g.link([controller:"species",action:"exportexp",params:[speciesName:"${species.scientificName}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}

                    objectInfo += "<b>Experiment Count:</b> ${linkExperiment}<br>"
                    objectInfo += "<b>Classes Count:</b> ${linkClass}<br>"
                    objectInfo += "<b>Samples Count:</b> ${linkSample}"
                }
                // End : Create dynamic link

                formatedList.add(["SrNo":++recCount,"discoveredInObj":discoveredInObj,"ObjectInfo":objectInfo,"ExperimentId":experimentId,"exportExperiment":exportExperiment])

            }else if( data instanceof OrganVO){//Process Searched Organs
                discoveredInObj = "Organ"
                def organ = (OrganVO)data
                //gLogger.info "organ :: ${organ}"

                experimentId = ""
                exportExperiment = ""

                objectInfo = "<b>Organ Name:</b> ${organ.organName}<br>"
                objectInfo += "<b>Species:</b> ${CommonUtil.getInstance().convertNameListIntoString(organ.species)}<br>"

                // Start : Create dynamic link
                if(organ?.experimentCount > 0){
                    def linkExperiment = g.link([controller:"organ",action:"datalist",params:[lookupBy:"experiments",organName:"${organ.organName}"]]) { organ?.experimentCount }
                    def linkClass = g.link([controller:"organ",action:"datalist",params:[lookupBy:"classes",organName:"${organ.organName}"]]) { organ?.classesCount }
                    def linkSample = g.link([controller:"organ",action:"datalist",params:[lookupBy:"samples",organName:"${organ.organName}"]]) { organ?.samplesCount }
                    exportExperiment = g.link([controller:"organ",action:"exportexp",params:[organName:"${organ.organName}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}

                    objectInfo += "<b>Experiment Count:</b> ${linkExperiment}<br>"
                    objectInfo += "<b>Classes Count:</b> ${linkClass}<br>"
                    objectInfo += "<b>Samples Count:</b> ${linkSample}"
                }
                // End : Create dynamic link

                formatedList.add(["SrNo":++recCount,"discoveredInObj":discoveredInObj,"ObjectInfo":objectInfo,"ExperimentId":experimentId,"exportExperiment":exportExperiment])

            }else if( data instanceof UserVO){//Process Searched Users
                discoveredInObj = "Collaboration or Owner "
                def user = (UserVO)data
                //gLogger.info "organ :: ${organ}"

                experimentId = ""
                exportExperiment = ""

                objectInfo = "<b>User Name:</b> ${user.displayName}<br>"
                objectInfo += "<b>eMail:</b> ${user.email}<br>"

                // Start : Create dynamic link
                if(user?.experimentCount > 0){
                    def linkExperiment = g.link([controller:"owner",action:"datalist",params:[lookupBy:"experiments",id:"${user.userId}"]]) { user?.experimentCount }
                    def linkClass = g.link([controller:"owner",action:"datalist",params:[lookupBy:"classes",id:"${user.userId}"]]) { user?.classesCount }
                    def linkSample = g.link([controller:"owner",action:"datalist",params:[lookupBy:"samples",id:"${user.userId}"]]) { user?.samplesCount }
                    exportExperiment = g.link([controller:"owner",action:"exportexp",params:[id:"${user.userId}","format":"excel","extension":"xls"],class:"exportexp",title:"Click to export experiment"]) {"&nbsp;&nbsp;"}

                    objectInfo += "<b>Experiment Count:</b> ${linkExperiment}<br>"
                    objectInfo += "<b>Classes Count:</b> ${linkClass}<br>"
                    objectInfo += "<b>Samples Count:</b> ${linkSample}"
                }
                // End : Create dynamic link

                formatedList.add(["SrNo":++recCount,"discoveredInObj":discoveredInObj,"ObjectInfo":objectInfo,"ExperimentId":experimentId,"exportExperiment":exportExperiment])

            }
        }
      }

      gLogger.info formatedList?.size
      gLogger.info "Out from prepareSearchAllResult method of FormatResultUtil"
      return ["fieldList":fieldList,"labelMap":labelMap,"formatters":formatters,"parameters":parameters,"cssClassMap":cssClassMap,"resultList":formatedList]
  }


}
